package cn.edu.hznu.util.network;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;

public class ChatRoomClient {
	private Selector selector;
	private final int port = 9999;
	private Charset charset = Charset.forName("utf-8");
	private SocketChannel socketChannel;
	private String name = "";
	private static String USER_EXIST = "system message: user exist, please change a name";
	private static String USER_CONTENT_SPILIT = "#@#";
	
	public void init() throws IOException {
		Selector selector = Selector.open();
		socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", port));
		socketChannel.configureBlocking(false);
		socketChannel.register(selector, SelectionKey.OP_READ);
		new Thread(() -> {
			try {
				while (true) {
						if (selector.select() == 0) {
							continue;
						}
						for (Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
								keyIterator.hasNext(); ) {
							processSelectionKey((SelectionKey) keyIterator.next());
							keyIterator.remove();
						}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}).start();
		Scanner scan = new Scanner(System.in);
		while (scan.hasNextLine()) {
			String line = scan.nextLine();
			if (line.isEmpty()) {
				continue;
			}
			if (name.isEmpty()) {
				name = line;
				line = name + USER_CONTENT_SPILIT;
			} else {
				line = name + USER_CONTENT_SPILIT + line;
			}
			socketChannel.write(charset.encode(line));
		}
	}
	
	private void processSelectionKey(SelectionKey key) throws IOException {
		if (key.isReadable()) {
			SocketChannel socketChannel = (SocketChannel) key.channel();
			ByteBuffer buf = ByteBuffer.allocate(1024);
			String content = "";
			while (socketChannel.read(buf) != -1) {
				buf.flip();
				content += charset.decode(buf);
				if (USER_EXIST.equals(content)) {
					name = "";
				}
				
				System.out.println(content);
				
				key.interestOps(SelectionKey.OP_READ);
			}
			
		}
	}
	
	public static void main(String[] args) {
		try {
			new ChatRoomClient().init();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
